<?php

namespace app\api\controller\wechat;


use Think\Session;
use think\Controller; // dengh quxiao
//use app\api\controller\common\SmsDemo;
use app\api\controller\common\AuthorCon;
use think\Db;

class Outcomtodoapi extends Controller
{
    private $config = [
        'other'=>[
            'appid'          => 'wx0047278096c532d9',
            'appsecret'      => '3655494ef775d05a7eaae321399bd1fd',
        ],
        'yt'=>[
            'appid'          => 'wxa73f6b3dd4b6da85',
            'appsecret'      => '6d5c1a0f016b49d8eb9943e276452635',
        ],
        'xcx'=>[
            'appid'          => 'wx0047278096c532d9',
            'appsecret'      => '3655494ef775d05a7eaae321399bd1fd',
        ]
    ];

    public function getWxConfig($wx_name){
        if($wx_name == 'yt' || $wx_name == 'xcx'){
            return $this->config[$wx_name];
        }
        return $this->config['other'];
    }

    public function getSignPackage()
    {
        $wxName =$this->request->param('wx_name');
        $appid=$this->getWxConfig($wxName)['appid'];
        $url = $this->request->param('url');
        $jsapiTicket = $this->getJsApiTicket($wxName);
//        var_dump($jsapiTicket);die();
        //$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=".$jsapiTicket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;
        $signature = sha1($string);
        $signPackage = array(
            "appId" => $appid,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return json(array('code' => '1', 'msg' => '成功','data'=>$signPackage));
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket($wxName)
    {

        $accessToken = $this->getAccessToken($wxName);
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $res = json_decode($this->httpGet($url));
        $ticket = $res->ticket;
        if ($ticket) {
            return $ticket;
        }
        return false;

    }

    private function getAccessToken($wxName)
    {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $appid=$this->getWxConfig($wxName)['appid'];
        $appSecret=$this->getWxConfig($wxName)['appsecret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
        $res = json_decode($this->httpGet($url));
        $access_token = $res->access_token;
        if ($access_token) {
            return $access_token;
        }
        return false;

    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }


    /**
     * 根据公海id获得获取
     * @return \think\response\Json|void
     *   https://xcx.gwsp.vip/api/wechat/Outcomtodoapi/wxSendTempinfo
     */
    public function wxSendTempinfo(){

        global $_W, $_GPC;
//        $openid=$_GPC['openid'];
//        $touser=$params['touser'];
//         var_dump(1111);die;
        $type="orderok";
        $params=array('kc_name'=>'sdf','teachername'=>1,'kc_price'=>23,'uname'=>33);
        if($type=="orderok"){
            $tempid="eA80w39lLSGPxjcu1UCvPXh_3Dq8qz2WwHLAToKaJgY";
//            $items=array('touser'=>$students['dad'],'uname'=>$students['s_name'],'kc_name'=>$kc_name,'kc_price'=>'('.$orderinfo['paytype_name'].')'.$orderinfo['cose'],
//                'teachername'=>$njzr['tname'],'schoolid'=>$order['schoolid'],'kcid'=>$tcourse['id']);
            $url="";// <a href='".$url."' >ces</a>
            // $url=$_W['siteroot'] . 'app/' .$this->createMobileUrl('kcinfo', array( 'schoolid' =>$params['schoolid'],'id'=>$params['kcid'] ));
            $first="恭喜你有成员下订单";
            $keyword1=$params['kc_name'];
            $keyword2=$params['teachername'];
            $keyword3=$params['kc_price'];
            $keyword4=date('Y-m-d');
            $keyword5=$params['uname'];
            $remark="感谢你，用心服务每一位家长！\n\n不开心和有压力的时候，\n深夜睡不着的时候，\n......，\n如何调频到喜悦和平？\n我们在听什么，\n";
            //$remark.="就会构建起心里的影像，\n进而构建外在的实相。\n今晚准时收听，{$params['kc_name']},\n就是选择了一种生活方式。";

        }elseif ($type=="kcup"){
            //课程更新通知
            // xLixhpYbow3wxvItuwpvbkoC12bzIkFe80b2bcmT4lM    uDPJAJ38EM5XVuAT6jLDc_6ixJi_2h-hNFojQFm4vgM
            $tempid="sSFFVloHB5OYwpJ5aY8WYZGvfVMgdtcM0yE2IyYIm2U";
            $first="课程上新通知";
            $url=$params['url'];
            $keyword1=$params['kc_name'];
            $keyword2=$params['kc_type']; // 课程类别
            $keyword3=$params['teachername'];
            $keyword4=date('Y-m-d');
            $remark="爱与教育深耕班，您教子路上最深情的陪伴~~";

            //var_dump(112);die;
        }elseif ($type=="cxjg"){
            // 查询结果通知
//            {{first.DATA}}
//            已上课时：{{keyword1.DATA}}
            //查询时间：{{keyword2.DATA}}
            //统计时间：{{keyword3.DATA}}
            //{{remark.DATA}}
            //
            // var_dump($params);die;
            $tempid="z8QvgA938lSlepSEmFbD19SpDcL3AHdbZnqD8vbI5QI";
            $first=$params['s_name']."你好,你的个人办公昨日数据如下";
            $url=$params['url'];
            $keyword1="";
            $keyword2=date('Y-m-d H:i:s'); // 查询时间
            $keyword3=date('Y-m-d H:i:s'); // 统计时间
            //$keyword4=date('Y-m-d');
            //var_dump(222);die;
            // $para=array('touser'=>$item1['own'],'s_name'=>$item1['s_name'],'url'=>$url,'down1count'=>$down1count,'down2count'=>$down2count);

            $remark="新增B级家长{$params['down1count']}人 \n新增C级家长{$params['down2count']}人\n新增家长共{$params['downtotal']}人";
            $remark.="\n爱与教育深耕班，您教子路上最深情的陪伴~~";

        }
        else{
            $first="";
            $keyword1="";
            $keyword2="";
            $keyword3="";
            $keyword4="";
            $keyword5="";
            $remark="";
        }

        //
        $template_data = array(
            'first' => array(   'value' => $first,
                'color' => '#ff510'),
            'keyword1' => array(
                'value' => $keyword1,
                'color' => '#000000'
            ),
            'keyword2' => array(
                'value' =>$keyword2,
                'color' => '#000000'
            ),
            'keyword3' => array(
                'value' => $keyword3,
                'color' => '#000000'
            ),
            'keyword4' => array(
                'value' => $keyword4,
                'color' => '#000000'
            ),
            'keyword5' => array(
                'value' => $keyword5,
                'color' => '#000000'
            ),
            'remark' => array(
                'value' => $remark ,
                'color' => '#000000'
            ),
        );
        //发送消息给推荐人  own zj   OKrw0tqzdeEUk4R6xws7SnAG9tLSzYpTC_bglRpbcng, eA80w39lLSGPxjcu1UCvPXh_3Dq8qz2WwHLAToKaJgY
        // ff510 墨绿
//        $account_api = WeAccount::create();
//
//        $res=$account_api->sendTplNotice($touser,$tempid,$template_data,$url);

//        return $res;
        // var_dump($account_api);die;

        $auth= new AuthorCon();
//        $com = new CommonPlus();


        $openid=array("o7HeyszY854vIz1ul66RkIODwP_0","o7Heys4PIp2o0MDhyrpdJWkY8ZL4","o7Heys_7VZWoff9MwQgIa4DaY51k");
        $template_id="ielXmf8lgMuyP-VVv_t1ND0C1L19HZ4hZAKxpCoguJs";
        $url="#";
        $title="客户：，已完成检测支付";
        $price="0.01";


        $where=" and from_unixtime(birthday,'%m-%d')='".date('m-d')."'";
        $list = Db::name('member_user')
            ->where("1=1 ".$where)
//            ->alias('a')
//            ->join('activity_cate b','a.cate_id=b.id')
            ->field('nickname,openid')
//            ->order('sort ASC')
//            ->limit(($page-1)*$pagesize.','.$pagesize)
            ->select();

//         var_dump($list);die;

        foreach ($list as $oid){
//            $this->sendMessage($oid,$template_id,$url,$title,$price);
            $res=$auth->sendBirthxcx($oid['openid'],$oid['nickname']);
        }


        //
        $openid="ofSRDw7QmwgU_tWCb7inQu48xVgM";
        $openid="oXZiH4pKWcB5vkftlCZaFtsXeuqA";// 小程序 兀

//        $res=$auth->sendBirth($openid);





    }



    /**
     * 提货通知
     *   https://xcx.gwsp.vip/api/wechat/Outcomtodoapi/wxSendTemptihuo
     */

    public function wxSendTemptihuo(){

        global $_W, $_GPC;
//        $openid=$_GPC['openid'];
//        $touser=$params['touser'];
         //var_dump(22);die;
        $type="orderok";
        $params=array('kc_name'=>'sdf','teachername'=>1,'kc_price'=>23,'uname'=>33);
        if($type=="orderok"){
            $tempid="eA80w39lLSGPxjcu1UCvPXh_3Dq8qz2WwHLAToKaJgY";
//            $items=array('touser'=>$students['dad'],'uname'=>$students['s_name'],'kc_name'=>$kc_name,'kc_price'=>'('.$orderinfo['paytype_name'].')'.$orderinfo['cose'],
//                'teachername'=>$njzr['tname'],'schoolid'=>$order['schoolid'],'kcid'=>$tcourse['id']);
            $url="";// <a href='".$url."' >ces</a>
            // $url=$_W['siteroot'] . 'app/' .$this->createMobileUrl('kcinfo', array( 'schoolid' =>$params['schoolid'],'id'=>$params['kcid'] ));
            $first="恭喜你有成员下订单";
            $keyword1=$params['kc_name'];
            $keyword2=$params['teachername'];
            $keyword3=$params['kc_price'];
            $keyword4=date('Y-m-d');
            $keyword5=$params['uname'];
            $remark="感谢你，用心服务每一位家长！\n\n不开心和有压力的时候，\n深夜睡不着的时候，\n......，\n如何调频到喜悦和平？\n我们在听什么，\n";
            //$remark.="就会构建起心里的影像，\n进而构建外在的实相。\n今晚准时收听，{$params['kc_name']},\n就是选择了一种生活方式。";

        }elseif ($type=="kcup"){
            //课程更新通知
            // xLixhpYbow3wxvItuwpvbkoC12bzIkFe80b2bcmT4lM    uDPJAJ38EM5XVuAT6jLDc_6ixJi_2h-hNFojQFm4vgM
            $tempid="sSFFVloHB5OYwpJ5aY8WYZGvfVMgdtcM0yE2IyYIm2U";
            $first="课程上新通知";
            $url=$params['url'];
            $keyword1=$params['kc_name'];
            $keyword2=$params['kc_type']; // 课程类别
            $keyword3=$params['teachername'];
            $keyword4=date('Y-m-d');
            $remark="爱与教育深耕班，您教子路上最深情的陪伴~~";

            //var_dump(112);die;
        }elseif ($type=="cxjg"){
            // 查询结果通知
//            {{first.DATA}}
//            已上课时：{{keyword1.DATA}}
            //查询时间：{{keyword2.DATA}}
            //统计时间：{{keyword3.DATA}}
            //{{remark.DATA}}
            //
            // var_dump($params);die;
            $tempid="z8QvgA938lSlepSEmFbD19SpDcL3AHdbZnqD8vbI5QI";
            $first=$params['s_name']."你好,你的个人办公昨日数据如下";
            $url=$params['url'];
            $keyword1="";
            $keyword2=date('Y-m-d H:i:s'); // 查询时间
            $keyword3=date('Y-m-d H:i:s'); // 统计时间
            //$keyword4=date('Y-m-d');
            //var_dump(222);die;
            // $para=array('touser'=>$item1['own'],'s_name'=>$item1['s_name'],'url'=>$url,'down1count'=>$down1count,'down2count'=>$down2count);

            $remark="新增B级家长{$params['down1count']}人 \n新增C级家长{$params['down2count']}人\n新增家长共{$params['downtotal']}人";
            $remark.="\n爱与教育深耕班，您教子路上最深情的陪伴~~";

        }
        else{
            $first="";
            $keyword1="";
            $keyword2="";
            $keyword3="";
            $keyword4="";
            $keyword5="";
            $remark="";
        }

        //
        $template_data = array(
            'first' => array(   'value' => $first,
                'color' => '#ff510'),
            'keyword1' => array(
                'value' => $keyword1,
                'color' => '#000000'
            ),
            'keyword2' => array(
                'value' =>$keyword2,
                'color' => '#000000'
            ),
            'keyword3' => array(
                'value' => $keyword3,
                'color' => '#000000'
            ),
            'keyword4' => array(
                'value' => $keyword4,
                'color' => '#000000'
            ),
            'keyword5' => array(
                'value' => $keyword5,
                'color' => '#000000'
            ),
            'remark' => array(
                'value' => $remark ,
                'color' => '#000000'
            ),
        );
        //发送消息给推荐人  own zj   OKrw0tqzdeEUk4R6xws7SnAG9tLSzYpTC_bglRpbcng, eA80w39lLSGPxjcu1UCvPXh_3Dq8qz2WwHLAToKaJgY
        // ff510 墨绿
//        $account_api = WeAccount::create();
//
//        $res=$account_api->sendTplNotice($touser,$tempid,$template_data,$url);

//        return $res;
        // var_dump($account_api);die;

        $auth= new AuthorCon();
//        $com = new CommonPlus();


        $openid=array("o7HeyszY854vIz1ul66RkIODwP_0","o7Heys4PIp2o0MDhyrpdJWkY8ZL4","o7Heys_7VZWoff9MwQgIa4DaY51k");
        $template_id="ielXmf8lgMuyP-VVv_t1ND0C1L19HZ4hZAKxpCoguJs";
        $url="#";
        $title="客户：，已完成检测支付";
        $price="0.01";


        $where=" and from_unixtime(birthday,'%m-%d')='".date('m-d')."'";
        $list = Db::name('member_user')
            ->where("1=1 ".$where)
//            ->alias('a')
//            ->join('activity_cate b','a.cate_id=b.id')
            ->field('nickname,openid')
//            ->order('sort ASC')
//            ->limit(($page-1)*$pagesize.','.$pagesize)
            ->select();

//         var_dump($list);die;

        foreach ($list as $oid){
//            $this->sendMessage($oid,$template_id,$url,$title,$price);
            $res=$auth->sendOrdertihuo($oid['openid'],$oid['nickname']);
        }


        //
        $openid="ofSRDw7QmwgU_tWCb7inQu48xVgM";
        $openid="oXZiH4pKWcB5vkftlCZaFtsXeuqA";// 小程序 兀

//        $res=$auth->sendBirth($openid);





    }




}
